import { Base } from './base';

export interface Keypair {
  privateKey: string;
  publicKey: string;
}

export type CipherMode = 0 | 1;

export interface Sm2 {
  generateKeyPairHex(): Keypair,

  doDecrypt(encryptData: string, privateKey: string, cipherMode: CipherMode): string
}

export class Passport extends Base {
  private sm2: Sm2;
  private keyPair: Keypair;
  private readonly urls: Record<string, string>;

  constructor(baseUrl: string, sm2: Sm2, headers?: Record<string, string>, urls?: Record<string, string>) {
    super(baseUrl);
    if (headers)
      this.setDefaultHeaders(headers);
    this.sm2 = sm2;
    this.keyPair = sm2.generateKeyPairHex();
    this.urls = urls || {
      scanner: '/skinny-passport/scanner',
      scannerShow: '/skinny-passport/scanner/show',
      scannerAuthorize: '/skinny-passport/scanner/authorize',
    };
  }

  getUrls() {
    return this.urls;
  }

  setSm2(sm2: Sm2) {
    this.sm2 = sm2;
  }

  async getScannerCode() {
    const code = this.keyPair.publicKey;
    const { data } = await super.get(this.urls.scanner, { code });
    return JSON.parse(this.sm2.doDecrypt(data, this.keyPair.privateKey, 1));
  }

  async showPassport(code: string, avatar?: string) {
    const { data } = await super.get(this.urls.scannerShow, { code, avatar });
    return data;
  }

  async authorize(code: string, status: 0 | 1) {
    return await super.post(`${this.urls.scannerAuthorize}/${code}/${status}`, {});
  }

}